<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Input,
  Textarea,
  Button
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';

import { useVbenForm } from '#/adapter/form';
import { getPage_smart, postPage_smart, putPage_smart } from '#/api/portal/home';
import { usePreferencesStore } from '#/store';

const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);


const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? $t('page.common.Add')+' '+`${routeTitle}`
    : `No.${index.value} - `+$t('page.common.Edit')+` ${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    title: '',
    des: '',
    content:[],
   
  },
  pageThemeFiles: [],
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.title;
          state.form.title = values.title;
          state.form.des = values.des;
          state.form.content = values.content;
          state.form.images = values.images;
        
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'des',
          'content',
          'images'
        ],
      },
      componentProps: {
        placeholder:$t('page.common.Please Enter')+' ('+$t('admin.maxChars', { length: 50 })+'）',
      },
      fieldName: 'title',
      label: `${routeTitle} `+$t('page.common.Title'),
      rules: z.string().max(50,$t('admin.maxChars', { length: 50 })),
    },

 
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'des',
      label: `${routeTitle} `+$t('page.common.Description'),
    },
       {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
        tips:'1190px-852px'
      },
      fieldName: 'images',
      label: $t("admin.backgroundImage"),
    },

    {
      component: 'content',
      defaultValue: [{name:'',content:''}],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'content',
      label:  `${routeTitle} `+ $t('page.common.Content'),
    },
       
  ],
});

const contentList = ref([{ name: '', content: '' }])  // 全局响应式声明


async function onSubmit() {
  function showMsg(msg: string) {
    message.success(msg);
   
      
  }
  const values: any = state.form;

  if (values.id) {
    const { msg } = await putPage_smart(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postPage_smart(values);
    showMsg(msg);
  }
}
async function onGetPage() {
  const { data } = await getPage_smart();
  data.post = {
    id: data?.id ?? undefined,
    title: data?.title ?? '',
    des: data?.des ?? '',
    content: data?.content ?? [{name:'',content:''}],
    images: data?.images ?? [{id:'',url:''}],
  };
  
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
  state.pageThemeFiles = data.pageThemeFiles;
   contentList.value = JSON.parse(JSON.stringify(data.post.content)) // 深拷贝防止引用污染
}

onMounted(async () => {
  await onGetPage();
  
});


// 更新 name
function onUpdateName(index, value) {
  contentList.value[index].name = value
  updateForm()
}

// 更新 content
function onUpdateContent(index, value) {
  contentList.value[index].content = value
  updateForm()
}

// 添加一项
function addContentItem() {
  contentList.value.push({ name: '', content: '' })
  updateForm()
}
function removeContentItem(index) {
  if (contentList.value.length <= 1) {
    return;
  }
  contentList.value.splice(index, 1);
  updateForm();
}


// 同步到表单字段
function updateForm() {
  BasicFormApi.setFieldValue('content', JSON.parse(JSON.stringify(contentList.value))) // 深拷贝同步表单
}

</script>

<template>
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm>

        <template #content>
          <div class="content_s" style="width:50%">
                <div v-for="(item, index) in contentList" :key="index" style="margin-top:10px;flex-direction: column">
                        <Input class="input"
                            v-model:value="item.name"
                            maxlength=50
                            :placeholder="$t('page.common.Please Enter')+'('+$t('admin.maxChars', { length: 50 })+')'"
                            @input="onUpdateName(index, $event.target.value)"
                            style="margin-bottom: 8px"
                        />
                        <Textarea class="textarea"
                            v-model:value="item.content"
                            rows="6"
                            :placeholder="$t('page.common.Please Enter')"
                            @input="onUpdateContent(index, $event.target.value)"
                        />
                        <div class="flex items-center justify-end gap-2 mt-3">
                           <Button type="dashed" @click="removeContentItem(index)">{{$t('page.common.Delete')}}</Button>
                           <Button type="dashed" @click="addContentItem">{{$t('page.common.Add')}}</Button>
                        </div>
                </div>
               <div>
                 
               
               </div>
          </div>  
          
          
        </template>
      </BasicForm>
    </Card>
  </Page>
</template>

<style lang="scss">
      .content_s{
        display: flex;
        gap: 25px;
        width: 100%;
        flex-direction: column;
         .input ,.textarea,.submit{
            width: 100%;
            display: block;
         }
         .textarea{
            min-height: 100px;
         }
      }
</style>>
